// 页面加载完成后执行
$(function () {
    loadAddressList(1, 5);
});

// 加载地址列表
function loadAddressList(pageNo = 1, pageSize = 5) {
    const $container = $('.address-list');

    // 显示加载中状态
    $container.html('<div class="loading">加载中...</div>');

    // 发送 AJAX 请求
    $.ajax({
        url: 'locationInfo',
        type: 'post',
        data: {
            pageNo: pageNo,
            pageSize: pageSize
        },
        dataType: 'json',
        success: function (response) {
            if (response.success) {
                renderAddressList(response.data, pageNo, pageSize);
            } else {
                showError(response.message);
            }
        }
    });
}

// 渲染地址列表
function renderAddressList(pageInfo, currentPage, pageSize) {
    const $container = $('.address-list');

    // 检查是否有数据
    if (!pageInfo.list || pageInfo.list.length === 0) {
        $container.html(
            '<div class="empty-state">' +
            '<p>亲，暂无邮寄地址，点击按钮进行添加~</p>' +
            '</div>'
        );
        return;
    }

    let html = '';

    // 渲染地址列表
    pageInfo.list.forEach(location => {
        html += '<div class="address-item">' +
            '<div class="address-info">' +
            '<div class="receiver-info">' +
            '<span class="name">' + location.receiverName + '</span>' +
            '<span class="mobile">' + location.mobilePhone + '</span>' +
            '</div>' +
            '<div class="address">' +
            location.province + ' ' + location.city + ' ' + location.district + ' ' + location.streetAddress +
            '</div>' +
            '<div class="contact-info">';

        // 电话号码部分
        if (location.phoneNumber) {
            html += '<span class="phone">电话：';
            if (location.areaCode) {
                html += location.areaCode + '-';
            }
            html += location.phoneNumber;
            if (location.extension) {
                html += '-' + location.extension;
            }
            html += '</span>';
        }

        // 邮政编码部分
        if (location.postalCode) {
            html += '<span class="postal">邮编：' + location.postalCode + '</span>';
        }

        html += '</div>' +
            '</div>' +
            '<div class="address-actions">' +
            '<button class="edit-btn" onclick="editLocation(' + location.id + ')">编辑</button>' +
            '<button class="delete-btn" onclick="deleteLocation(' + location.id + ')">删除</button>' +
            '</div>' +
            '</div>';
    });

    // 添加分页控件
    if (pageInfo.totalPages > 1) {
        html += '<div class="pagination">';

        // 上一页
        if (currentPage > 1) {
            html += '<a href="javascript:void(0)" onclick="loadAddressList(' + (currentPage - 1) + ', ' + pageSize + ')">上一页</a>';
        }

        // 第一页
        if (currentPage > 3) {
            html += '<a href="javascript:void(0)" onclick="loadAddressList(1, ' + pageSize + ')">1</a>';
            if (currentPage > 4) {
                html += '<span class="ellipsis">...</span>';
            }
        }

        // 当前页码附近的页码
        for (let i = Math.max(1, currentPage - 2); i <= Math.min(pageInfo.totalPages, currentPage + 2); i++) {
            if (i === parseInt(currentPage)) {
                html += '<span class="current-page">' + i + '</span>';
            } else {
                html += '<a href="javascript:void(0)" onclick="loadAddressList(' + i + ', ' + pageSize + ')">' + i + '</a>';
            }
        }

        // 最后一页
        if (currentPage < pageInfo.totalPages - 2) {
            if (currentPage < pageInfo.totalPages - 3) {
                html += '<span class="ellipsis">...</span>';
            }
            html += '<a href="javascript:void(0)" onclick="loadAddressList(' + pageInfo.totalPages + ', ' + pageSize + ')">' + pageInfo.totalPages + '</a>';
        }

        // 下一页
        if (currentPage < pageInfo.totalPages) {
            html += '<a href="javascript:void(0)" onclick="loadAddressList(' + (currentPage + 1) + ', ' + pageSize + ')">下一页</a>';
        }

        html += '</div>';
    }

    // 渲染到容器
    $container.html(html);
}

// 删除地址
function deleteLocation(id) {
    if (!confirm('确定要删除这个地址吗？')) {
        return;
    }

    $.ajax({
        url: 'deleteLocation',
        type: 'POST',
        data: {id: id},
        dataType: 'json',
        success: function (response) {
            if (response.success) {
                alert('删除成功');
                // 重新加载当前页
                loadAddressList($('.pagination .current-page').text() || 1);
            } else {
                alert(response.message || '删除失败');
            }
        },
        error: function () {
            alert('网络错误，请稍后重试');
        }
    });
}

// 编辑地址
function editLocation(id) {
    window.location.href = 'editLocation.jsp?id=' + id;
}

// 显示错误信息
function showError(message) {
    const $container = $('.address-list');
    $container.html(
        '<div class="error-state">' +
        '<p>' + message + '</p>' +
        '<button onclick="loadAddressList()">重试</button>' +
        '</div>'
    );
}

